<template>
  <div class="upload-goods" v-loading="loading">
    <el-row :gutter="20" type="flex"  justify="center">
      <el-col :span="20">
        <el-card class="box-card"  shadow="always" style="box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);">
          <el-steps :active="active" finish-status="success" align-center process-status="finish">
            <el-step title="选择商品分类"></el-step>
            <el-step title="填写商品信息"></el-step>
            <el-step title="填写商品属性"></el-step>
          </el-steps>
          <div style="padding-top: 30px;padding-left: 120px" v-loading="loading">
            <div v-show="active === 0" style="height: 500px">
              <el-form ref="form" :model="dateForm" label-width="100px" >
                <!-- <el-form-item label="上传类型：">
                  <el-radio v-model="dateForm.priceType" @change="typeChange" label="1" border>兑换商城</el-radio>
                  <el-radio v-model="dateForm.priceType" @change="typeChange" label="2" border>福利商城</el-radio>
                </el-form-item> -->
                <el-form-item label="选择分类：" >
                  <el-cascader v-model="dateForm.classId" :options="classList" :props="props" expand-trigger="hover" filterable @change="
                  dateForm.goodsInventoryDetail = []
                  skuTemp = []
                  dateForm.brandClassId = ''
                  getSpecsList(true)"></el-cascader>
                </el-form-item>
                <el-form-item label="品牌选择: ">
                  <el-select v-model.trim="dateForm.brandClassId" filterable placeholder="选择/搜索品牌">
                    <!--<el-option :value="-1" :key="-1" label="请选择"></el-option>-->
                    <el-option
                      v-for="(item,index) in brandList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <div v-show="active === 1">
              <!-- <div>
                <h2 >通过淘宝上传商品</h2>
              </div>
              <el-form label-width="100px" >
                <el-form-item label="淘宝链接：">
                  <el-input type="textarea" :rows="2" placeholder="淘宝链接" v-model="taobaoUrl"></el-input>
                  <el-button type="text" @click="getGoodsDetailByUrl">获取</el-button>
                </el-form-item>
              </el-form> -->
              <div>
                <h2 >通过ID上传商品</h2>
              </div>
              <el-form label-width="100px" >
                <el-form-item label="链接地址：">
                  <el-input :rows="2" type="textarea" placeholder="url" v-model="dateForm.poizonId"></el-input>
                  <el-button type="text" @click="clickPoizon">获取</el-button>
                </el-form-item>
              </el-form>
              <div>
                <h2 >基础信息</h2>
              </div>
              <el-form ref="rules" :model="dateForm" label-width="100px" :rules="rules" id="dateForm">
                <!--<el-form-item label="品牌：">-->
                  <!--<el-input placeholder="请输入品牌"></el-input>-->
                <!--</el-form-item>-->
                <el-form-item label="商品名称："  prop="goodsName">
                  <el-input type="textarea" placeholder="请输入商品名称" v-model="dateForm.goodsName" :rows="4"></el-input>
                </el-form-item>
                <!-- <el-form-item label="seo关键字：" >
                  <el-input placeholder="seo关键字,用逗号隔开" v-model="dateForm.seoKeywords"
                            type="textarea"></el-input>
                </el-form-item> -->
                <el-form-item label="seo描述：" >
                  <el-input placeholder="seo描述（商品功效 例如：高露洁牙膏） 这里可以写：美白、高效、方便、植物等功效"
                            v-model="dateForm.seoDescription"
                            type="textarea" :rows="4"></el-input>
                </el-form-item>
                <!-- <el-form-item label="商品简要：">
                  <el-input placeholder="请输入商品简要" v-model="dateForm.goodsBrief"
                            type="textarea"></el-input>
                </el-form-item> -->
                <el-form-item label="商品服务：">
                  <el-checkbox-group v-model="dateForm.goodsServerId" @change="handleCheckedCitiesChange">
                    <el-checkbox v-for="item in this.serviceList" :label="item.id" :key="item">{{item.serviceName}}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="运费模板：" prop="freightId">
                  <el-select v-model="dateForm.freightId" placeholder="运费模板">
                    <el-option
                      v-for="item in dateForm.freightList"
                      :key="item.freightId"
                      :label="item.freightTitle"
                      :value="item.freightId">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="商品原价："  prop="goodsPrice">
                  <el-input placeholder="请输入商品原价" v-model="dateForm.goodsPrice"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                      list.price = dateForm.goodsPrice
                    })"
                  ></el-input>
                </el-form-item>
                <!-- <el-form-item label="商城售价：" v-if="dateForm.priceType !== '1'"  prop="vipPrice">
                  <el-input placeholder="请输入商城售价" v-model="dateForm.vipPrice"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                      list.vipPrice = dateForm.vipPrice
                    })">
                  </el-input>
                </el-form-item> -->
                <el-form-item label="商城售价：" prop="vipPrice">
                  <el-input placeholder="请输入商城售价" v-model="dateForm.vipPrice"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                      list.vipPrice = dateForm.vipPrice
                      list.giveIntegral = dateForm.giveIntegral
                    })">
                  </el-input>
                </el-form-item>
                <!-- <el-form-item :label="dateForm.priceType === '1'?'兑换消耗券:' : '赠送积分:'" v-if=""  prop="integral">
                  <el-input :placeholder="dateForm.priceType === '1'? '请输入兑换消耗（积分）':'请输入赠送积分'" v-model="dateForm.integral"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                      list.integral = dateForm.integral
                    })"></el-input>
                </el-form-item> -->
                <el-form-item label="赠送积分方式:" prop="giveIntegralType">
                  <template>
                    <el-radio v-model="dateForm.giveIntegralType" :label="1" @change="queryGiveIntegralType(dateForm.giveIntegralType)">1：1赠送</el-radio>
                    <el-radio v-model="dateForm.giveIntegralType" :label="2" @change="queryGiveIntegralType(dateForm.giveIntegralType)">2：1赠送</el-radio>
                    <el-radio v-model="dateForm.giveIntegralType" :label="3" @change="queryGiveIntegralType(dateForm.giveIntegralType)" v-if="dateForm.buyerPrice != 0">进价赠送</el-radio>
                  </template>
                  <el-input placeholder="赠送积分" v-model="dateForm.giveIntegral"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                      list.giveIntegral = dateForm.giveIntegral
                    })" disabled></el-input>
                </el-form-item>
                <!-- <el-form-item :label="dateForm.priceType === '1'?'兑换消耗券:' : '赠送积分:'" prop="integral">
                  <el-input :placeholder="dateForm.priceType === '1'? '请输入兑换消耗（积分）':'请输入赠送积分'" v-model="dateForm.integral"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                      list.integral = dateForm.integral
                    })"></el-input>
                </el-form-item> -->
                <el-form-item label="商品进价:" prop="buyerPrice">
                  <el-input placeholder="请输入商品进价" v-model="dateForm.buyerPrice"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                      list.buyerPrice = dateForm.buyerPrice
                    })"></el-input>
                </el-form-item>
                <el-form-item label="兑换积分:" prop="integral">
                  <el-input placeholder="请输入兑换消耗积分" v-model="dateForm.integral"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                      list.integral = dateForm.integral
                    })"></el-input>
                </el-form-item>
                <el-form-item label="商品利润："  prop="goodsCostingPrice">
                  <el-input placeholder="请输入商品利润" :disabled="dateForm.priceType === '1'" v-model="dateForm.goodsCostingPrice"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                      list.goodsCostingPrice = dateForm.goodsCostingPrice
                      })"></el-input>
                </el-form-item>
                <!-- <el-form-item label="运费：" prop="expressTransFee">
                  <el-input placeholder="请输入运费" v-model="dateForm.expressTransFee" :disabled="dateForm.goodsTransfee === 1"></el-input>
                </el-form-item> -->

                <el-form-item label="商品条型码：" prop="goodsSn">
                  <el-input placeholder="请输入商品条型码" v-model.trim="dateForm.goodsSn"></el-input>
                </el-form-item>

                <el-form-item label="商品型号：" prop="goodsSerial">
                  <el-input placeholder="请输入商品型号" v-model="dateForm.goodsSerial" :disabled="this.dateForm.id !== 0" @change="verificationGoodsSerial"></el-input>
                </el-form-item>
                <el-form-item label="库存："  prop="goodsInventory">
                  <el-input placeholder="请输入库存" v-model="dateForm.goodsInventory"
                            @change="dateForm.goodsInventoryDetail.map(list => {
                    list.count = dateForm.goodsInventory
                    })">
                  </el-input>
                </el-form-item>
                <el-form-item label="库存预警："  prop="warnNumber">
                  <el-input placeholder="请输入库存预警" v-model="dateForm.warnNumber"></el-input>
                </el-form-item>
                <el-form-item label="启动销量："  prop="goodsSaleNum">
                  <el-input placeholder="请输入启动销量" v-model="dateForm.goodsSaleNum"></el-input>
                </el-form-item>
                <el-form-item label="商品主图：">
                  <el-upload
                    :limit="1"
                    :before-upload="checkFile"
                    list-type="picture-card"
                    :action="action"
                    :on-preview="handlePreview"
                    :file-list="dateForm.mainImg"
                    :on-success="handleSuccess"
                    :on-remove="handleRemove"
                    :on-exceed="onExceed">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
                <el-form-item label="商品轮播图：">
                  <el-upload
                    list-type="picture-card"
                    :before-upload="checkFile1"
                    :action="action"
                    :on-preview="handlePreview"
                    :file-list="dateForm.rollingImg"
                    :on-success="handleSuccessRolling"
                    :on-remove="handleRemoveRolling">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
                <el-form-item label="商品视频：">
                  <el-upload
                    class="avatar-uploader"
                    :action="action"
                    accept='.mp4,.qlv,.qsv,.ogg,.flv,.avi,.wmv,.rmvb'
                    :show-file-list="false"
                    :before-upload="beforeUploadVideo"
                    :on-success="handleVideoSuccess"
                    :on-progress="uploadVideoProcess">
                      <video
                        v-if="this.dateForm.video !== '' && this.dateForm.video.length !== 0 && this.videoFlag === false"
                        :src="this.dateForm.video[0].url"
                        width="350"
                        height="180"
                        controls="controls">您的浏览器不支持视频播放</video>
                      <i v-else-if="this.dateForm.video === null && this.videoFlag === false" class="el-icon-plus avatar-uploader-icon"></i>
                      <el-progress
                        v-if="this.videoFlag === true"
                        type="circle"
                        :percentage="videoUploadPercent"
                        style="margin-top:30px">
                      </el-progress>
                  </el-upload>
                  <p>如果是视频轮播图，请在这里上传视频资源，最多只能上传一个&nbsp;&nbsp;<el-button type="primary" v-show="this.dateForm.video !== '' && this.dateForm.video.length !== 0 && this.videoFlag === false" @click="deleteVideo()">移除视频</el-button></p>
                  </el-form-item>
                <!--<el-form-item label="是否包邮" >-->
                  <!--<el-switch-->
                    <!--v-model="dateForm.goodsTransfee">-->
                  <!--</el-switch>-->
                <!--</el-form-item>-->
              </el-form>

              <!--<div>-->
                <!--<h2 >特殊信息</h2>-->
              <!--</div>-->
              <!--<el-form ref="form" :model="dateForm" label-width="100px" >-->
                <!--<el-form-item label="阶梯价格：">-->
                  <!--<el-switch>-->
                  <!--</el-switch>-->
                  <!--<el-button  type="text" size="small" @click="addTable('ladderPrice')">增加</el-button>-->
                  <!--<el-table-->
                    <!--:data="ladderPriceList" border style="width: 50%">-->
                    <!--<el-table-column-->
                      <!--prop="num"-->
                      <!--align="center"-->
                      <!--label="数量/件">-->
                      <!--<template slot-scope="scope">-->
                        <!--<el-input v-model="scope.row.num"></el-input>-->
                      <!--</template>-->
                    <!--</el-table-column>-->
                    <!--<el-table-column-->
                      <!--prop="money"-->
                      <!--align="center"-->
                      <!--label="减多少/元">-->
                      <!--<template slot-scope="scope">-->
                        <!--<el-input v-model="scope.row.money"></el-input>-->
                      <!--</template>-->
                    <!--</el-table-column>-->
                    <!--<el-table-column-->
                      <!--label="操作"-->
                      <!--align="center"-->
                      <!--width="80">-->
                      <!--<template slot-scope="scope">-->
                        <!--<el-button  type="text" size="small" @click="removeTable(scope.$index,'ladderPrice')">删除</el-button>-->
                      <!--</template>-->
                    <!--</el-table-column>-->
                  <!--</el-table>-->
                <!--</el-form-item>-->
                <!--<el-form-item label="满减：">-->
                  <!--<el-switch>-->
                  <!--</el-switch>-->
                  <!--<el-button  type="text" size="small" @click="addTable('fullMinus')">增加</el-button>-->
                  <!--<el-table-->
                    <!--:data="fullMinusList" border style="width: 50%">-->
                    <!--<el-table-column-->
                      <!--prop="num"-->
                      <!--align="center"-->
                      <!--label="数量/件">-->
                      <!--<template slot-scope="scope">-->
                        <!--<el-input v-model="scope.row.num"></el-input>-->
                      <!--</template>-->
                    <!--</el-table-column>-->
                    <!--<el-table-column-->
                      <!--prop="money"-->
                      <!--align="center"-->
                      <!--label="减多少/元">-->
                      <!--<template slot-scope="scope">-->
                        <!--<el-input v-model="scope.row.money"></el-input>-->
                      <!--</template>-->
                    <!--</el-table-column>-->
                    <!--<el-table-column-->
                      <!--label="操作"-->
                      <!--align="center"-->
                      <!--width="80">-->
                      <!--<template slot-scope="scope">-->
                        <!--<el-button  type="text" size="small" @click="removeTable(scope.$index,'fullMinus')">删除</el-button>-->
                      <!--</template>-->
                    <!--</el-table-column>-->
                  <!--</el-table>-->
                <!--</el-form-item>-->
              <!--</el-form>-->
              <div>
                <h2 >商品详情</h2>
              </div>
              <UEditor ref="ueditor"></UEditor>
            </div>
            <div v-show="active === 2" style="width: 1030px;">
              <div class="specs">
                <h2>选择规格</h2>
                <el-card class="card" v-for="(item,index) in specsList" key="card">
                  <el-row :gutter="20">
                    <el-col :span="5">
                      <div style="padding-left: 10px;padding-bottom: 10px;font-size: 16px;color: #17B3A3;">{{item.name}}</div>

                    </el-col>
                    <el-col :span="5" v-for="(pItem,index) in item.property" key="property">
                      <el-checkbox v-model="checkboxData" :label="pItem.id" @change="dateForm.checkBoxChangeFlag = 1
                      isSpecsUpdate = false
                      checkboxClick(item,pItem)">{{pItem.name}}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-card>
              </div>
              <div>
                <h2>自定义规格</h2>
                <el-button type="primary" plain icon="el-icon-plus" @click="customVisible = true">添加自定义规格</el-button>
                <div class="custom">
                  <el-dialog
                    title="自定义规格"
                    :visible.sync="customVisible"
                    width="30%">
                    <el-form ref="customSpecs" :model="customSpecs" label-width="80px">
                      <el-form-item label="规格">
                        <!-- <el-input v-model="customSpecs.name"></el-input> -->
                        <el-radio v-model="customSpecs.name" label="规格">规格</el-radio>
                        <el-radio v-model="customSpecs.name" label="颜色">颜色</el-radio>
                      </el-form-item>
                      <el-form-item label="规格属性">
                        <el-tag
                          :key="tag.name"
                          v-for="(tag,index) in customSpecs.property"
                          closable
                          :disable-transitions="false"
                          @close="handleClose(index)">
                          {{tag.name}}
                        </el-tag>
                        <el-input
                          class="input-new-tag"
                          v-if="inputVisible"
                          v-model="inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm"
                          @blur="handleInputConfirm">
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加</el-button>
                      </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                      <el-button @click="customVisible = false">取 消</el-button>
                      <el-button type="primary" @click="addCustomSpecs">确 定</el-button>
                    </span>
                  </el-dialog>
                </div>
              </div>
              <div>
                <h2 >设定价格及库存&nbsp;&nbsp;<el-button type="primary" @click="randomGoodsInventory">随机规格库存</el-button></h2>
                <el-form :model="dateForm"  ref="rules">
                  <el-table
                    class="specs-table"
                    :border="true"
                    :data="dateForm.goodsInventoryDetail">
                    <el-table-column
                      prop="imgPath"
                      label="规格图"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <el-upload
                          class="avatar-uploader"
                          :action="action"
                          :show-file-list="false"
                          :before-upload="checkFile"
                          :on-success="((res, file, fileList) => {skuImgSuccessSpec(res, file, fileList ,scope.$index)})">
                          <img style="max-width: 80px" v-if="scope.row.imgPath" :src="scope.row.imgPath" class="avatar">
                          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                      </template>
                    </el-table-column>
                    <el-table-column
                      :key="item"
                      v-for="item in skuListColumn"
                      :prop="item.prop"
                      :label="item.label"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <span>{{skuProperty[scope.row[item.prop][0]][scope.row[item.prop][1]]}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="vipPrice"
                      label="商城售价"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.vipPrice`" :rules='rules.vipPrice'>
                          <el-input v-model="scope.row.vipPrice" placeholder="" size="mini" @change="updateSpecPrice(scope.$index, scope.row.vipPrice)"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="price"
                      label="商品原价"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.price`" :rules='rules.price'>
                          <el-input :disabled="true" v-model="scope.row.price" placeholder="" size="mini"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="giveIntegral"
                      label="赠送积分"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.giveIntegral`" :rules='rules.giveIntegral'>
                          <el-input :disabled="true" v-model="scope.row.giveIntegral" placeholder="" size="mini"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="count"
                      label="库存数量"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.count`" :rules='rules.goodsInventory'>
                          <el-input v-model="scope.row.count" placeholder="" size="mini"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="integral"
                      label="兑换积分"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.integral`" :rules='rules.integral'>
                          <el-input v-model="scope.row.integral" placeholder="" size="mini"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="goodsCostingPrice"
                      label="商品利润"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.goodsCostingPrice`"  :rules='rules.goodsCostingPrice'>
                          <el-input v-model="scope.row.goodsCostingPrice" placeholder="" size="mini"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="buyerPrice"
                      label="商品进价"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.buyerPrice`"  :rules='rules.buyerPrice'>
                          <el-input v-model="scope.row.buyerPrice" placeholder="" size="mini"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="weight"
                      label="重量/g"
                      header-align="center"
                      align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.weight`" :rules='rules.weight'>
                          <el-input v-model="scope.row.weight" placeholder="" size="mini"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="startExpDate"
                      label="开始时间"
                      header-align="center"
                      align="center"
                      v-if="false">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.startExpDate`">
                          <el-input v-model="scope.row.startExpDate" placeholder="" size="mini"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="endExpDate"
                      label="结束时间"
                      header-align="center"
                      align="center"
                      v-if="false">
                      <template slot-scope="scope">
                        <el-form-item :prop="`goodsInventoryDetail.${scope.$index}.endExpDate`">
                          <el-input v-model="scope.row.endExpDate" placeholder="" size="mini"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      fixed="right"
                      header-align="center"
                      align="center"
                      label="操作">
                      <template slot-scope="scope">
                        <el-button type="text" size="small" @click="deleteHandle(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form>
              </div>
              <div v-if="skuListColumn.length !== 0">
                <h2 >添加规格图</h2>
                <el-select  placeholder="规格名" size="small" v-model="specsImgSelect" style="margin-bottom: 20px" value="">
                  <el-option
                    @click="isSpecsUpdate = false"
                    :key="item.id"
                    v-for="item in skuListColumn"
                    :id="item.id"
                    :label="item.label"
                    :value="item.id"></el-option>
                </el-select>

                <div class="specsImg">
                  <el-row v-if="specsImgSelect !== '' " :gutter="20"
                          v-for="(item,index) in skuProperty[specsImgSelect]" :key="index">
                    <el-col :span="4">
                      {{item}}
                    </el-col>
                    <el-col :span="16">
                      <el-upload
                        :action="action"
                        :before-upload="checkFile"
                        class="avatar-uploader"
                        :show-file-list="false"
                        :on-success="((res, file, fileList) => {skuImgSuccess(res, file, fileList ,index)})">
                        <img v-if="specsImgList[index] !== undefined" :src="specsImgList[index]" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </div>
            <!--<div v-if="active === 3">选择商品关联</div>-->
            <el-row :gutter="20" type="flex"  justify="center">
              <el-button style="margin-top: 12px;" @click="back" v-if="active !== 0">上一步</el-button>
              <el-button style="margin-top: 12px;" @click="next" type="primary" plain v-if="active !== 2">下一步</el-button>
              <el-button style="margin-top: 12px;" type="primary" v-else @click="upload" :disabled="checkFlag">完成</el-button>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import UEditor from '@/components/ueditor/ueditor.vue'
  import axios from 'axios'

  import qs from 'qs'
export default {
    data: function () {
      var checkNumber = (rule, value, callback) => {
        if (typeof value === 'object' || value === undefined) {
          value = rule.field
        }
        let reg = /^[1-9]\d*$/
        if (!reg.test(value)) {
          callback(this.$message.error('积分应为正整数！'))
        } else {
          callback()
        }
      }
      var checkWeight = (rule, value, callback) => {
        if (typeof value === 'object' || value === undefined) {
          value = rule.field
        }
        let reg = /^[1-9]\d*$/
        if (!reg.test(value)) {
          callback(this.$message.error('重量应为正整数！'))
        } else {
          callback()
        }
      }
      var checkNumber2 = (rule, value, callback) => {
        if (typeof value === 'object' || value === undefined) {
          value = rule.field
        }
        let reg = /^[0-9]\d*$/
        if (!reg.test(value)) {
          callback(this.$message.error('库存及销量应为正整数！'))
        } else {
          callback()
        }
      }
      var checkNumberfee = (rule, value, callback) => {
        if (typeof value === 'object' || value === undefined) {
          value = rule.field
        }
        let reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/
        if (!reg.test(value)) {
          callback(this.$message.error('运费不规范！'))
        } else {
          callback()
        }
      }
      var checkCostingPrice = (rule, value, callback) => {
        if (typeof value === 'object' || value === undefined) {
          value = rule.field
        }
        let reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/
        if (value < 0 || !reg.test(value)) {
          callback(this.$message.error('最多只能保留小数点后两位！'))
        } else {
          callback()
        }
        // let reg = /^(^[0-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,}$)$/
        // if (Number.parseFloat(value) < 0 || !reg.test(value) || !Number.isFinite(Number.parseFloat(value))) {
        //   callback(this.$message.error('商品利润不规范！'))
        // } else if (value > this.dateForm.vipPrice * 0.5) {
        //   callback(new Error('利润不得大于售价的50%'))
        // } else {
        //   callback()
        // }
      }
      var checkDecimal = (rule, value, callback) => {
        if (typeof value === 'object' || value === undefined) {
          value = rule.field
        }
        let reg = /^(^[0-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,}$)$/
        if (Number.parseFloat(value) <= 0 || !reg.test(value) || !Number.isFinite(Number.parseFloat(value))) {
          // callback(new Error('数据不合法'))
          callback(this.$message.error('商品原价或售价不规范！'))
        } else {
          callback()
        }
      }
      return {
        videoFlag: false,
        videoUploadPercent: '0',
        dialogFormVisible: false,
        customVisible: false,
        checkFlag: false,
        inputVisible: false,
        inputValue: '',
        customSpecs: {
          property: [],
          name: ''
        },
        action: '',
        specsImgIndex: '',
        specsImgList: {},
        active: 0,
        loading: false,
        skuListIndex: 0,
        skuTemp: [],
        taobaoUrl: '',
        dateForm: {
          poizonId: '',
          video: [],
          photoId: 0,
          id: 0,
          priceType: '2',
          goodsSn: '',
          goodsSerial: '',
          goodsBrief: '',
          addTime: '',
          goodsName: '',
          goodsPrice: '',
          integral: '',
          warnNumber: 50,
          goodsTransfee: 0, // 0不包邮  1包邮
          expressTransFee: 0,
          goodsInventory: '',
          goodsSaleNum: '',
          goodsCostingPrice: 0,
          vipPrice: '',
          seoKeywords: '',
          seoDescription: '',
          classId: [], // 数组两个值
          rollingImg: [],
          mainImg: [],
          gcId: 0,
          goodsInventoryDetail: [],
          deleteRollingImgId: new Set(),
          checkBoxChangeFlag: 0,
          isActivityGoods: 0,
          activityTitle: '',
          giveIntegralType: 1,
          giveIntegral: 0,
          buyerPrice: 0,
          goodsServerId: [],
          specDetails: [],
          brandClassId: '',
          freightList: [],
          freightId: ''
        },
        classList: [],
        specsList: [],
        serviceList: [],
        brandList: [],
        props: {
          value: 'id',
          label: 'className',
          children: 'subGoodsClassList'
        },
        dialogImageUrl: '',
        dialogVisible: false,
        fullMinusList: [{
          num: 0,
          money: 0
        }],
        ladderPriceList: [{
          num: 0,
          money: 0
        }],
        checkboxData: [],
        uploadFlag: 0,
        skuListColumn: [],
        skuProperty: [],
        skuColumnCorrespondence: [],
        // 规格图上传时选中的规格
        specsImgSelect: '',
        isSpecsUpdate: true,
        rules: {
          goodsSerial: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          goodsName: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          freightId: [
            { required: true, message: '运费模板不能为空', trigger: 'blur' }
          ],
          goodsPrice: [
            { validator: checkDecimal, required: true, trigger: 'blur' }
          ],
          price: [
            { validator: checkDecimal, required: true, trigger: 'blur' }
          ],
          vipPrice: [
            { validator: checkDecimal, required: true, trigger: 'blur' }
          ],
          integral: [
            { validator: checkNumber, required: true, trigger: 'blur' }
          ],
          goodsCostingPrice: [
            { validator: checkCostingPrice, required: true, trigger: 'blur' }
          ],
          goodsInventory: [
            { validator: checkNumber2, required: true, trigger: 'blur' }
          ],
          warnNumber: [
            { validator: checkNumber2, required: true, trigger: 'blur' }
          ],
          goodsSaleNum: [
            { validator: checkNumber2, required: true, trigger: 'blur' }
          ],
          expressTransFee: [
            { validator: checkNumberfee, required: true, trigger: 'blur' }
          ],
          weight: [
            { validator: checkWeight, required: true, trigger: 'blur' }
          ]
        }
      }
    },
    components: {
      UEditor
    },
    activated () {
      this.getDataList()
    },
    watch: {
      'dateForm.isActivityGoods': function (val) {
        if (val > 0) {
          this.$message('该商品已经添加到 【' + this.dateForm.activityTitle + '】限时活动中')
          return false
        }
      },
      'dateForm.vipPrice': function (val) {
        if (!this.dateForm.id) {
          if (this.dateForm.giveIntegralType === 1) {
            if ((/^[0-9]*[1-9][0-9]*$/.test(val))) {
              this.dateForm.giveIntegral = val
            } else {
              let price = val.split('.')
              this.dateForm.giveIntegral = Number(price[0])
            }
          } else {
            if ((/^[0-9]*[1-9][0-9]*$/.test(this.dateForm.vipPrice))) {
              let endPrice = Number(this.dateForm.vipPrice) / 2
              if ((/^[0-9]*[1-9][0-9]*$/.test(endPrice))) {
                this.dateForm.giveIntegral = endPrice
              } else {
                this.dateForm.giveIntegral = Number(endPrice.split('.')[0])
              }
            } else {
              let startPrice = (this.dateForm.vipPrice / 2) + ''
              let price = startPrice.split('.')
              this.dateForm.giveIntegral = Number(price[0])
            }
          }
        }
      },
      'dateForm.buyerPrice': function (val) {
        if (!this.dateForm.id) {
          if (val !== 0) {
            let exchange = val * 14.28
            if ((/^[0-9]*[1-9][0-9]*$/.test(exchange))) {
              this.dateForm.integral = exchange
            } else {
              let a = exchange + ''
              let b = a.split('.')
              this.dateForm.integral = Number(b[0]) + 1
            }
          }
          for (let h = 0; h < this.dateForm.goodsInventoryDetail.length; h++) {
            this.dateForm.goodsInventoryDetail[h].integral = this.dateForm.integral
          }
        }
        if (this.dateForm.giveIntegralType === 3) {
          this.dateForm.giveIntegral = Math.floor(this.dateForm.buyerPrice)
          this.dateForm.goodsCostingPrice = ((this.dateForm.vipPrice - this.dateForm.buyerPrice) / 0.7).toFixed(2)
          this.dateForm.goodsInventoryDetail.map(list => { list.goodsCostingPrice = this.dateForm.goodsCostingPrice })
        }
      },
      'dateForm.goodsSerial': function (val) {
        if (val !== '' && val != null) {
          this.$http({
            url: this.$http.adornUrl(`/goods/verificationGoodsSerial/${val}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              if (data.data !== 0 && this.dateForm.id === 0) {
                this.$message.error('该型号已经存在')
                this.dateForm.goodsSerial = ''
              }
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      }
    },
    methods: {
      handleCheckedCitiesChange (value) {
        if (value.length > 0) {
          this.dateForm.goodsServerId = []
          let a = value.length
          for (var n = 0; n < a; n++) {
            this.dateForm.goodsServerId.push(value[n])
          }
        } else {
          this.dateForm.goodsServerId = []
        }
      },
      typeChange () {
        if (this.dateForm.priceType === '1') {
          // 兑换
          this.dateForm.vipPrice = 0
          this.dateForm.goodsCostingPrice = 0
        } else {
          this.dateForm.expressTransFee = 0
        }
      },
      handleClose (index) {
        this.customSpecs.property.splice(index, 1)
      },
      showInput () {
        this.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      handleInputConfirm: function () {
        let inputValue = this.inputValue
        if (inputValue) {
          this.customSpecs.property.push({id: 0, name: inputValue})
        }
        this.inputVisible = false
        this.inputValue = ''
      },
      queryGiveIntegralType (type) {
        if (type === 1) {
          if ((/^[0-9]*[1-9][0-9]*$/.test(this.dateForm.vipPrice))) {
            this.dateForm.giveIntegral = this.dateForm.vipPrice
          } else {
            let price = this.dateForm.vipPrice.split('.')
            this.dateForm.giveIntegral = Number(price[0])
          }
        } else if (type === 2) {
          if ((/^[0-9]*[1-9][0-9]*$/.test(this.dateForm.vipPrice))) {
            let endPrice = Number(this.dateForm.vipPrice) / 2 + ''
            if ((/^[0-9]*[1-9][0-9]*$/.test(endPrice))) {
              this.dateForm.giveIntegral = Number(endPrice)
            } else {
              this.dateForm.giveIntegral = Number(endPrice.split('.')[0])
            }
          } else {
            let startPrice = (this.dateForm.vipPrice / 2) + ''
            let price = startPrice.split('.')
            this.dateForm.giveIntegral = Number(price[0])
          }
        } else {
          this.dateForm.giveIntegral = Math.floor(this.dateForm.buyerPrice)
          this.dateForm.goodsCostingPrice = ((this.dateForm.vipPrice - this.dateForm.buyerPrice) / 0.7).toFixed(2)
          this.dateForm.goodsInventoryDetail.map(list => { list.goodsCostingPrice = this.dateForm.goodsCostingPrice })
          // for (let q = 0; q < this.dateForm.goodsInventoryDetail.length; q++) {
          //   this.dateForm.goodsInventoryDetail[q].giveIntegral = this.dateForm.giveIntegral
          // }
        }
        for (let q = 0; q < this.dateForm.goodsInventoryDetail.length; q++) {
          this.dateForm.goodsInventoryDetail[q].giveIntegral = this.dateForm.giveIntegral
        }
      },
      updateSpecPrice (index, price) {
        debugger
        if (this.dateForm.giveIntegralType === 1) {
          if ((/^[0-9]*[1-9][0-9]*$/.test(price))) {
            this.dateForm.goodsInventoryDetail[index].giveIntegral = price
          } else {
            let price1 = price.split('.')
            this.dateForm.goodsInventoryDetail[index].giveIntegral = Number(price1[0])
          }
        } else if (this.dateForm.giveIntegralType === 2){
          if ((/^[0-9]*[1-9][0-9]*$/.test(price))) {
            debugger
            let endPrice = Number(price) / 2 + ''
            if ((/^[0-9]*[1-9][0-9]*$/.test(endPrice))) {
              this.dateForm.goodsInventoryDetail[index].giveIntegral = Number(endPrice)
            } else {
              this.dateForm.goodsInventoryDetail[index].giveIntegral = Number(endPrice.split('.')[0])
            }
          } else {
            let startPrice1 = parseInt(price) / 2
            // let price2 = startPrice1.split('.')
            this.dateForm.goodsInventoryDetail[index].giveIntegral = Math.floor(startPrice1)
          }
        } else {
          this.dateForm.goodsInventoryDetail[index].giveIntegral = this.dateForm.giveIntegral
        }
      },
      // 视频上传之前判断他的大小
      beforeUploadVideo (file) {
        debugger
        const isLt10M = file.size / 1024 / 1024 < 10
        if (!isLt10M) {
          this.$message.error('上传视频大小不能超过10MB哦!')
          return false
        }
      },
      // 视频上传的时候获取上传进度传给进度条
      uploadVideoProcess (event, file, fileList) {
        this.videoFlag = true
        this.videoUploadPercent = parseInt(file.percentage)
      },
      // 视频上传成功之后返回视频地址
      handleVideoSuccess (res, file) {
        this.videoFlag = false
        this.videoUploadPercent = 0
        let v = []
        v.push({'id': 0, 'url': res.data})
        if (this.dateForm.video.length > 0) {
          this.dateForm.deleteRollingImgId.add(this.dateForm.video[0].id)
        }
        this.dateForm.video = v
      },
      init (id) {
        // 商品运费模板
        this.$http({
          url: this.$http.adornUrl('/freight/queryEnableFreightList'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 100
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dateForm.freightList = data.data.list
          }
        })
        this.loading = false
        this.$refs.ueditor.setUEContent('')
        this.getDataList()
        this.dateForm.id = id || 0
        this.$nextTick(() => {
          if (this.dateForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/goods/getGoodsById/${this.dateForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dateForm.goodsInventoryDetail = JSON.parse(data.data.goodsInventoryDetail)
                this.skuTemp = this.dateForm.goodsInventoryDetail
                // this.skuTemp = JSON.parse(data.data.goodsInventoryDetail)
                console.log(this.dateForm.goodsInventoryDetail)
                console.log(this.skuTemp)
                this.dateForm.gcId = data.data.gcId
                this.dateForm.classId = [data.data.parentGcId, data.data.gcId]
                this.getSpecsList()
                console.log(this.dateForm.goodsInventoryDetail)
                this.dateForm.photoId = data.data.photoId
                this.dateForm.goodsName = data.data.goodsName
                this.dateForm.photoId = data.data.photoId
                this.$set(this.dateForm.mainImg, 0, {id: data.data.photoId, url: data.data.img})
                // this.dateForm.rollingImg = data.data.rotationChart
                if (data.data.rotationChart != null && data.data.rotationChart.length > 0) {
                  for (var a = 0; a < data.data.rotationChart.length; a++) {
                    let fileSuffix = data.data.rotationChart[a].url.substring(data.data.rotationChart[a].url.lastIndexOf('.') + 1)
                    if (fileSuffix === 'jpg' || fileSuffix === 'png') {
                      this.dateForm.rollingImg.push({'id': data.data.rotationChart[a].id, 'url': data.data.rotationChart[a].url})
                    } else {
                      this.dateForm.video.push({'id': data.data.rotationChart[a].id, 'url': data.data.rotationChart[a].url})
                    }
                  }
                }
                if (this.dateForm.video.length <= 0) {
                  this.videoFlag = true
                }
                  // this.dateForm.rollingImg.push({id: i, url: pic1[i].imgSrc})
                this.dateForm.goodsInventory = data.data.goodsInventory
                this.dateForm.seoKeywords = data.data.seoKeywords
                this.dateForm.seoDescription = data.data.seoDescription
                this.dateForm.warnNumber = data.data.warnNumber
                this.dateForm.goodsPrice = data.data.goodsPrice
                this.dateForm.vipPrice = data.data.vipPrice
                this.dateForm.goodsCostingPrice = data.data.goodsCostingPrice
                this.dateForm.goodsSerial = data.data.goodsSerial
                this.dateForm.expressTransFee = data.data.expressTransFee
                this.dateForm.goodsBrief = data.data.goodsBrief
                this.dateForm.integral = data.data.integral
                this.dateForm.priceType = data.data.priceType.toString()
                this.dateForm.goodsSn = data.data.goodsSn
                this.$refs.ueditor.setUEContent(data.data.goodsDetails)
                this.dateForm.goodsSaleNum = data.data.goodsSaleNum.toString()
                this.dateForm.isActivityGoods = data.data.isActivityGoods
                this.dateForm.activityTitle = data.data.activityTitle
                this.dateForm.addTime = data.data.addTime
                this.dateForm.brandClassId = data.data.goodsBrandId != null ? data.data.goodsBrandId : ''
                this.dateForm.giveIntegralType = data.data.giveIntegralType
                this.dateForm.giveIntegral = data.data.giveIntegral
                this.dateForm.buyerPrice = data.data.buyerPrice
                if (data.data.goodsServerId != null && data.data.goodsServerId !== '') {
                  this.dateForm.goodsServerId = data.data.goodsServerId.split(',')
                }
                this.dateForm.freightId = data.data.freightId
              }
            })
          }
        })
      },
      // 获取数据列表
      getDataList () {
        this.action = this.$http.adornUrl(`/goods/uploadImg?token=${this.$cookie.get('token')}`)
        // 请求分类
        this.$http({
          url: this.$http.adornUrl(`/activity/goods/queryClassList`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.classList = data.data
          }
        })
        // 请求服务
        this.$http({
          url: this.$http.adornUrl(`/service/queryGoodsServiceList`),
          method: 'get',
          params: this.$http.adornParams({
            'page': 0,
            'limit': 100
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.serviceList = data.data.list
          }
        })
        // 商品运费模板
        this.$http({
          url: this.$http.adornUrl('/freight/queryEnableFreightList'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 100
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dateForm.freightList = data.data.list
          }
        })
      },
      // 获取规格数据
      getSpecsList (flag) {
        debugger
        this.$nextTick(function () {
          this.$http({
            url: this.$http.adornUrl(`/goods/querySpecsList/` + this.dateForm.classId[1] || this.dateForm.classId[0]),
            method: 'get'
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.specsList = data.data
              // 回显规格数据
              if (flag !== null && this.dateForm.id !== 0) {
                let than = this
                than.checkboxData = []
                let idSet = new Set()
                this.dateForm.goodsInventoryDetail.map(gid => gid.id.split('_')).forEach(function (value) {
                  value.forEach(function (val) {
                    if (val !== '' && Number.isInteger(Number.parseInt(val))) {
                      val = Number.parseInt(val)
                      idSet.add(val)
                    }
                  })
                })
                idSet.forEach(function (val) {
                  let ification = than.specsList.filter(item => item.property.map(p => {
                    return p.id
                  }).includes(val))[0]

                  let property
                  if (ification !== undefined) {
                    property = ification.property.filter(item => item.id === val)[0]
                    than.checkboxClick(ification, property)
                    than.checkboxData.push(val)
                  } else {
                    // 自定义规格
                    let customSpecs = null
                    than.getCustomSpecs(val).then(data => {
                      customSpecs = data
                      if (customSpecs !== null) {
                        ification = customSpecs
                        // property = customSpecs.property[0]
                        property = customSpecs.property.filter(p => p.id === val)[0]
                        if (than.specsList.filter(list => list.id === data.id).length === 0) {
                          than.specsList.push(customSpecs)
                        } else {
                          than.specsList.map(list => {
                            if (list.id === data.id) {
                              // than.specsList.push(customSpecs)
                              list.property.push(property)
                            }
                          })
                        }
                        than.checkboxClick(ification, property)
                        than.checkboxData.push(val)
                      }
                    })
                  }
                })
              }
            }
          })
          // 请求关联品牌
          debugger
          this.$http({
            url: this.$http.adornUrl(`/brand/queryBrandList/` + this.dateForm.classId[1]),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.brandList = data.data
            }
          })
        })
        if (!this.dateForm.id) {
          debugger
          this.videoFlag = true
        }
      },
      next () {
        this.loading = true
        if (this.active === 0) {
          debugger
          if (this.dateForm.classId.length === 0) {
            this.$message.error('分类不能为空')
            this.loading = false
            return
          }
        }
        if (!this.dateForm.id) {
          // 默认服务全部选中
          for (let aa = 0; aa < this.serviceList.length; aa++) {
            this.dateForm.goodsServerId.push(this.serviceList[aa].id)
          }
        }
        if (this.active++ > 1) this.active = 0

        // 初始化sku里的数据
        if (this.dateForm.id === 0 && this.active === 2) {
          if (this.dateForm.goodsInventoryDetail.length === 0 || this.dateForm.goodsInventoryDetail.length === 1) {
            this.dateForm.goodsInventoryDetail = []
            this.dateForm.goodsInventoryDetail.push({
              imgPath: '',
              goodsCostingPrice: this.dateForm.goodsCostingPrice || 0,
              integral: this.dateForm.integral || 0,
              count: this.dateForm.goodsInventory || 0,
              price: this.dateForm.goodsPrice || 0,
              vipPrice: this.dateForm.vipPrice || 0,
              showCostingPrice: 0,
              priceType: this.dateForm.priceType || 0,
              buyerPrice: this.dateForm.buyerPrice || 0,
              giveIntegral: this.dateForm.giveIntegral || 0,
              startExpDate: '',
              endExpDate: '',
              weight: 1
            })
          }
        }
        this.loading = false
      },
      back () {
        this.loading = true
        this.active--
        this.loading = false
      },
      handlePreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      checkFile (file) {
        let suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (suffix !== 'jpg' && suffix !== 'png' && suffix !== 'JPG' && suffix !== 'PNG') {
          this.$message.error('上传文件只能是 jpg、png格式!')
          return false
        }

        if (file.size > 1024 * 1024) {
          this.$message.error('上传图片大小不能超过1M！')
          return false
        }
      },
      checkFile1(file) {
        let suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (suffix !== 'jpg' && suffix !== 'png' && suffix !== 'JPG' && suffix !== 'PNG') {
          this.$message.error('上传文件只能是 jpg、png格式!')
          return false
        }
        if (file.size > 1024 * 1024) {
          this.$message.error('上传图片大小不能超过1M！')
          return false
        }
        // if (file.size > 1024 * 1024 * 10) {
        //   this.$message.error('上传图片大小不能超过10M！')
        //   return false
        // }
        // if (suffix === 'mp4' || suffix === 'MP4') {
        //   for (var k = 0; k < this.dateForm.rollingImg.length; k++) {
        //     let isAdd = this.dateForm.rollingImg[k].url.substring(this.dateForm.rollingImg[k].url.lastIndexOf('.') + 1)
        //     if (isAdd === 'mp4' || isAdd === 'MP4') {
        //       this.$message.error('最多只能上传一个视频')
        //       return false
        //     }
        //   }
        // }
      },
      // 文件上传成功的钩子函数
      handleSuccess (res, file, fileList) {
        if (res.code === 0) {
          this.$message({
            type: 'info',
            message: '图片上传成功',
            duration: 1000
          })
          this.dateForm.mainImg.push({id: this.dateForm.photoId, url: res.data})
        } else {
          this.$message({
            type: 'error',
            message: '图片上传失败',
            duration: 1000
          })
        }
      },
      // 删除文件之前的钩子函数
      handleRemove: function (file, fileList) {
        if (file.status !== 'ready') {
          this.dateForm.mainImg.splice(
            this.dateForm.mainImg.findIndex(v => v.url === file.url)
            , 1)
          this.$message({
            type: 'info',
            message: '已删除原有图片',
            duration: 1000
          })
        }
      },
      // 文件上传成功的钩子函数
      handleSuccessRolling (res, file, fileList) {
        // debugger
        // let suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
        // if (suffix === 'mp4' || suffix === 'MP4') {
        //   for (var k = 0; k < this.dateForm.rollingImg.length; k++) {
        //     let isAdd = this.dateForm.rollingImg[k].url.substring(this.dateForm.rollingImg[k].url.lastIndexOf('.') + 1)
        //     if (isAdd === 'mp4' || isAdd === 'MP4') {
        //       this.$message.error('最多只能上传一个视频')
        //       return false
        //     }
        //   }
        // }
        // debugger
        if (res.code === 0) {
          this.$message({
            type: 'info',
            message: '图片上传成功',
            duration: 1000
          })
          this.$set(this.dateForm.rollingImg, this.dateForm.rollingImg.length, {id: 0, url: res.data})
        } else {
          this.$message({
            type: 'error',
            message: '图片上传失败',
            duration: 1000
          })
        }
      },
      // 删除文件之前的钩子函数
      handleRemoveRolling (file, fileList) {
        if (file.status !== 'ready') {
          this.dateForm.rollingImg.splice(
          this.dateForm.rollingImg.findIndex(v => v.url === file.url)
          , 1)
          if (this.dateForm.id !== 0) {
            this.dateForm.deleteRollingImgId.add(file.id)
          }
          this.$message({
            type: 'info',
            message: '已删除原有图片',
            duration: 1000
          })
        }
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传1个图片',
          duration: 1000
        })
      },
      // 文件上传成功的钩子函数
      skuImgSuccess (res, file, fileList, index) {
        debugger
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 1000
        })
        if (res.code === 0) {
          this.$set(this.specsImgList, index, res.data)
        }
      },
      skuImgSuccessSpec (res, file, fileList, index) {
        console.log(this.dateForm.goodsInventoryDetail)
        // debugger
        // this.$message({
        //   type: 'info',
        //   message: '图片上传成功',
        //   duration: 1000
        // })
        if (res.code === 0) {
          this.$message({
            type: 'info',
            message: '图片上传成功',
            duration: 1000
          })
          this.dateForm.goodsInventoryDetail[index].imgPath = res.data
          this.dateForm.specDetails.push({'index': index, 'img': res.data})
        } else {
          this.$message({
            type: 'error',
            message: '图片上传失败',
            duration: 1000
          })
        }
      },
      deleteVideo () {
        this.dateForm.deleteRollingImgId.add(this.dateForm.video[0].id)
        this.videoFlag = true
        this.dateForm.video = []
      },
      removeTable (index, type) {
        if (type === 'fullMinus') {
          this.fullMinusList.splice(index, 1)
        } else if (type === 'ladderPrice') {
          this.ladderPriceList.splice(index, 1)
        }
      },
      addTable (type) {
        if (type === 'fullMinus') {
          this.fullMinusList.push({})
        } else if (type === 'ladderPrice') {
          this.ladderPriceList.push({})
        }
      },
      upload () {
        if (this.dateForm.freightId == null || this.dateForm.freightId === '') {
          this.$message.error('运费模板不能为空')
          return
        }
        if (this.dateForm.video.length > 0) {
          this.dateForm.rollingImg.push({'id': this.dateForm.video[0].id, 'url': this.dateForm.video[0].url})
        }
        if (this.dateForm.goodsSn != null && this.dateForm.goodsSn !== '' && this.dateForm.goodsSn.length > 0) {
          let a = 0
          let b = 0
          if (this.dateForm.goodsSn.length !== 13) {
            this.$message.error('条型码输入有误，请重新输入')
            return
          }
          for (var i = 0; i < this.dateForm.goodsSn.length; i++) {
            if (i % 2 !== 0) {
              let x = this.dateForm.goodsSn.charAt(i) - 0
              a = a + x
            } else {
              let y = this.dateForm.goodsSn.charAt(i) - 0
              b = b + y
            }
          }
          let lastOne = this.dateForm.goodsSn.charAt(this.dateForm.goodsSn.length - 1) - 0
          let c = (a * 3 + (b - lastOne) + '')
          let d = 10 - (c.charAt(c.length - 1) - 0)
          if (lastOne !== (d === 10 ? 0 : d)) {
            this.$message.error('条型码输入有误，请重新输入')
            return
          }
        }
        if (this.dateForm.isActivityGoods > 0) {
          this.$message.error('这款商品已经添加到限时活动中，暂不可修改！')
          return false
        }
        // if (this.dateForm.goodsInventoryDetail === undefined ||
        //   this.dateForm.goodsInventoryDetail.length === 0 ||
        //   this.dateForm.rollingImg.length === 0 ||
        //   this.dateForm.mainImg.length === 0) {
        //   this.$message.error('数据填写有误，请检查')
        //   return
        // }
        if (this.dateForm.goodsInventoryDetail === undefined || this.dateForm.goodsInventoryDetail.length === 0) {
          this.$message.error('至少商品有一种规格')
          return
        }
        if (this.dateForm.rollingImg.length === 0 || this.dateForm.mainImg.length === 0) {
          this.$message.error('主图和轮播图不能为空')
          return
        }
        let state
        this.$refs.rules.validate((result) => {
          if (!result) {
            state = true
          }
        })
        if (state) {
          this.$message.error('数据填写有误，请检查')
          return
        }

        let specsImgListKey = null
        specsImgListKey = Object.keys(this.specsImgList) || []
        if (!this.isSpecsUpdate && specsImgListKey.length === 0) {
          this.$message.error('请上传规格图片')
          return
        }
        // if (this.dateForm.id === 0) {
        //   // 规格图片
        //   specsImgListKey = Object.keys(this.specsImgList) || []
        //   if (!this.isSpecsUpdate && specsImgListKey.length === 0) {
        //     this.$message.error('请上传规格图片')
        //     return
        //   }
        // }
        // if (this.dateForm.goodsInventoryDetail.length > 0) {
        //   for (var i = 0; i < this.dateForm.goodsInventoryDetail.length; i++) {
        //     if (this.dateForm.id > 0) {
        //       debugger
        //       console.log(this.dateForm.goodsInventoryDetail[i].column1.length)
        //       if (this.dateForm.goodsInventoryDetail[i].column1.length <= 0) {
        //         let p = i + 1
        //         this.$message.error('该商品的第' + p + '个规格未绑定上属性，请重新定义或勾选')
        //         return
        //       }
        //     }
        //   }
        // }
        this.dateForm.gcId = this.dateForm.classId[1] || this.dateForm.classId[0]
        // 最大利润
        let maxGoodsCostingPrice = 0
        // 最小价格 福利商场价格
        let minPrice = 99999999
        // 总库存
        let countGoodsInventory = 0

        // sku的最小价格里的现金券
        let integral
        console.log(this.dateForm.goodsInventoryDetail)
        console.log(this.skuTemp)
        for (let i = 0; i < this.dateForm.goodsInventoryDetail.length; i++) {
          let reg = /^(^[0-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,}$)$/
          if (Number.parseFloat(this.dateForm.goodsInventoryDetail[i].vipPrice) <= 0 || !reg.test(this.dateForm.goodsInventoryDetail[i].vipPrice) || !Number.isFinite(Number.parseFloat(this.dateForm.goodsInventoryDetail[i].vipPrice))) {
            this.$message.error('商品原价或售价不规范！')
            return false
          }
          this.dateForm.goodsInventoryDetail[i].priceType = this.dateForm.priceType
          this.dateForm.goodsInventoryDetail[i].id = ''
          let keys = Object.keys(this.dateForm.goodsInventoryDetail[i])
          for (let j = 0; j < keys.length; j++) {
            if (keys[j].indexOf('column') !== -1) {
              let tempId = this.dateForm.goodsInventoryDetail[i][keys[j]][1]
              // 如果没有修改过，就使用最开始的规格图
              if (this.isSpecsUpdate) {
                this.dateForm.goodsInventoryDetail[i].imgPath = this.skuTemp[i].imgPath
              } else {
                // 修改过使用新的规格图
                if (specsImgListKey != null && specsImgListKey.indexOf(tempId) !== -1) {
                  this.dateForm.goodsInventoryDetail[i].imgPath = this.specsImgList[tempId]
                }
              }

              this.dateForm.goodsInventoryDetail[i].id += `${tempId}_`
              delete this.dateForm.goodsInventoryDetail[i][keys[j]]
            }
          }

          let tempPrice = 0
          let tempIntegral
          if (Number.parseInt(this.dateForm.priceType) === 1) {
            tempPrice = this.dateForm.goodsInventoryDetail[i].integral
          } else {
            tempPrice = this.dateForm.goodsInventoryDetail[i].vipPrice
            tempIntegral = this.dateForm.goodsInventoryDetail[i].integral

            // 展示利润 是利润的70%
            debugger
            // this.dateForm.goodsInventoryDetail[i].showCostingPrice = Math.floor(this.dateForm.goodsInventoryDetail[i].goodsCostingPrice * 0.7)
            this.dateForm.goodsInventoryDetail[i].showCostingPrice = (this.dateForm.goodsInventoryDetail[i].goodsCostingPrice * 0.7).toFixed(2)

            // 计算最大利润
            let goodsCostingPrice = this.dateForm.goodsInventoryDetail[i].goodsCostingPrice
            if (Number.parseFloat(goodsCostingPrice) > Number.parseFloat(maxGoodsCostingPrice)) {
              maxGoodsCostingPrice = goodsCostingPrice
            }
          }

          // 计算最小的价格
          if (Number.parseFloat(tempPrice) < Number.parseFloat(minPrice)) {
            minPrice = tempPrice
            integral = tempIntegral
          }
          countGoodsInventory += Number.parseInt(this.dateForm.goodsInventoryDetail[i].count)
        }
        if (this.dateForm.goodsInventoryDetail.length > 0) {
          for (var i = 0; i < this.dateForm.goodsInventoryDetail.length; i++) {
            debugger
            console.log(this.dateForm.goodsInventoryDetail[i].length)
            // if (this.dateForm.goodsInventoryDetail[i].id === '') {
            //   let p = i + 1
            //   this.$message.error('该商品的第' + p + '个规格未绑定上属性，请重新定义或勾选')
            //   return
            // }
            if (this.dateForm.goodsInventoryDetail[i].imgPath === '') {
              let p = i + 1
              this.$message.error('该商品的第' + p + '个规格图片未绑定上，请重新上传')
              return
            }
          }
        }
        debugger
        if (this.dateForm.specDetails.length > 0) {
          for(var p = 0; p < this.dateForm.specDetails.length; p++) {
            console.log(this.dateForm.specDetails[p].img)
            console.log(this.dateForm.goodsInventoryDetail[this.dateForm.specDetails[p].index].imgPath)
            this.dateForm.goodsInventoryDetail[this.dateForm.specDetails[p].index].imgPath = this.dateForm.specDetails[p].img
          }
        }
        this.loading = true
        debugger
        console.log(this.$refs.ueditor.getUEContent())
        this.$http({
          url: this.$http.adornUrl(`/goods/${this.dateForm.id !== 0 ? 'modifyGoodsById' : 'uploadGoods'}`),
          method: 'post',
          data: this.$http.adornData({
            'id': this.dateForm.id,
            'priceType': this.dateForm.priceType,
            'goodsSn': this.dateForm.goodsSn,
            'goodsSerial': this.dateForm.goodsSerial,
            'goodsBrief': this.dateForm.goodsBrief,
            'goodsInventoryDetail': JSON.stringify(this.dateForm.goodsInventoryDetail),
            'goodsName': this.dateForm.goodsName,
            'goodsPrice': this.dateForm.goodsPrice,
            'integral': this.dateForm.priceType === '1' ? minPrice : integral,
            'warnNumber': this.dateForm.warnNumber,
            'goodsTransfee': this.dateForm.goodsTransfee ? 1 : 0,
            'expressTransFee': this.dateForm.expressTransFee,
            // 'goodsInventory': this.dateForm.goodsInventory,
            'goodsInventory': countGoodsInventory,
            'goodsSaleNum': this.dateForm.goodsSaleNum,
            // 'goodsCostingPrice': this.dateForm.goodsCostingPrice,
            'goodsCostingPrice': maxGoodsCostingPrice,
            // 'vipPrice': this.dateForm.vipPrice,
            'vipPrice': this.dateForm.priceType === '2' ? minPrice : 0,
            'seoKeywords': this.dateForm.seoKeywords,
            'seoDescription': this.dateForm.seoDescription,
            'rollingImg': this.dateForm.rollingImg,
            'mainImg': this.dateForm.mainImg,
            'gcId': this.dateForm.gcId,
            'goodsDetails': this.$refs.ueditor.getUEContent(),
            'deleteRollingImgId': this.dateForm.deleteRollingImgId,
            'checkBoxChangeFlag': this.dateForm.checkBoxChangeFlag,
            'addTime': this.dateForm.addTime,
            'giveIntegral': this.dateForm.giveIntegral,
            'buyerPrice': this.dateForm.buyerPrice,
            'giveIntegralType': this.dateForm.giveIntegralType,
            'goodsServerId': this.dateForm.goodsServerId.join(','),
            'goodsBrandId': Number(this.dateForm.brandClassId) != '' ? this.dateForm.brandClassId : null,
            'freightId': this.dateForm.freightId,
            'transportId': this.dateForm.poizonId
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.loading = false
            this.$message({type: 'info', message: '操作成功', duration: 1000})

            if (this.dateForm.id !== 0) {
              this.$emit('refreshDataList')
            }
            this.$refs.ueditor.setUEContent('')
            Object.assign(this.$data, this.$options.data())
            this.getDataList()
          } else {
            this.$message.error(data.msg)
            // location.reload()
          }
        })
        // if (this.dateForm.id !== 0) {
        //   this.$emit('refreshDataList')
        // }
        // Object.assign(this.$data, this.$options.data())
        // this.getDataList()
        // location.reload()
      },
      deleteHandle (id) {
        this.dateForm.goodsInventoryDetail.splice(id, 1)
      },
      checkboxClick (ification, property) {
        // 添加规格属性
        let flag = this.addProperty(ification.id, property)
        if (flag === undefined) {
          flag = false
        }
        if (!flag) {
          // 添加规格
          this.addIfication(ification)
        }
        let keys = Object.keys(this.skuProperty)
        let list = []
        for (let i = 0; i < keys.length; i++) {
          list.push(this.skuProperty[keys[i]])
        }
        let data = this.doCombination(list, keys) || []
        this.dateForm.goodsInventoryDetail = []
        for (let x = 0; x < data.length; x++) {
          let row = data[x]
          for (let j = 0; j < row.length; j++) {
            let spliceData = row[j].split('-')
            let correspondenceKeys = Object.keys(this.skuColumnCorrespondence)
            for (let y = 0; y < correspondenceKeys.length; y++) {
              if (this.skuColumnCorrespondence[correspondenceKeys[y]].id === Number.parseInt(spliceData[0])) {
                if (typeof this.dateForm.goodsInventoryDetail[x] === 'undefined') {
                  if (typeof this.skuTemp[x] === 'undefined') {
                    this.dateForm.goodsInventoryDetail.push({imgPath: '',
                      goodsCostingPrice: this.dateForm.goodsCostingPrice || 0,
                      integral: this.dateForm.integral || 0,
                      count: this.dateForm.goodsInventory || 0,
                      price: this.dateForm.goodsPrice || 0,
                      vipPrice: this.dateForm.vipPrice || 0,
                      priceType: this.dateForm.priceType || 0,
                      buyerPrice: this.dateForm.buyerPrice || 0,
                      giveIntegral: this.dateForm.giveIntegral || 0,
                      startExpDate: '',
                      endExpDate: '',
                      weight: 1
                    })
                  } else {
                    this.dateForm.goodsInventoryDetail.push({imgPath: this.skuTemp[x].imgPath || '',
                      goodsCostingPrice: this.skuTemp[x].goodsCostingPrice || this.dateForm.goodsCostingPrice || 0,
                      integral: this.skuTemp[x].integral || this.dateForm.integral || 0,
                      count: this.skuTemp[x].count || this.dateForm.goodsInventory || 0,
                      price: this.skuTemp[x].price || this.dateForm.goodsPrice || 0,
                      vipPrice: this.skuTemp[x].vipPrice || this.dateForm.vipPrice || 0,
                      priceType: this.skuTemp[x].priceType || this.dateForm.priceType || 0,
                      buyerPrice: this.skuTemp[x].buyerPrice || this.dateForm.buyerPrice || 0,
                      giveIntegral: this.skuTemp[x].giveIntegral || this.dateForm.giveIntegral || 0,
                      startExpDate: this.skuTemp[x].startExpDate || '',
                      endExpDate: this.skuTemp[x].endExpDate || '',
                      weight: this.skuTemp[x].weight || 1
                    })
                  }
                }
                this.dateForm.goodsInventoryDetail[x][correspondenceKeys[y]] = spliceData
              }
            }
          }
        }
      },
      addProperty (pId, property) {
        debugger
        let pKeys = Object.keys(this.skuProperty)
        if (Object.keys(this.skuProperty).length !== 0) {
          let keys = Object.keys(this.skuProperty[pId] || [])
          for (let i = 0; i < keys.length; i++) {
            // 已存在属性列表里 移除属性
            if (keys.indexOf(property.id.toString()) !== -1) {
              delete this.skuProperty[pId][property.id]
              if (Object.keys(this.skuProperty[pId]).length === 0) {
                // this.skuProperty.splice(pKeys.indexOf(pId.toString()), 1)
                delete this.skuProperty[pId]
                // 规格属性为空时，删除表头
                for (let j = 0; j < this.skuListColumn.length; j++) {
                  if (this.skuListColumn[j].id === pId) {
                    let prop = this.skuListColumn[j].prop
                    delete this.skuColumnCorrespondence[prop]
                    this.skuListColumn.splice(j, 1)
                    // 删除表格数据里对应的属性数据
                    for (let x = 0; x < this.dateForm.goodsInventoryDetail.length; x++) {
                      delete this.dateForm.goodsInventoryDetail[x][prop]
                    }
                    return true
                  }
                }
              }
              return true
            }
          }
        }

        if (pKeys.indexOf(pId.toString()) === -1) {
          this.skuProperty[pId] = {}
        }
        this.skuProperty[pId][property.id] = property.name
      },
      addIfication (ification) {
        for (let i = 0; i < this.skuListColumn.length; i++) {
          if (this.skuListColumn[i].id === ification.id) {
            return
          }
        }
        let columnName = 'column' + (this.skuListColumn.length + 1)
        this.skuColumnCorrespondence[columnName] = {id: ification.id,
          label: ification.name}
        this.skuListColumn.push({id: ification.id,
          prop: columnName,
          label: ification.name})
        // console.log(this.dateForm.goodsInventoryDetail)
        // if (this.dateForm.goodsInventoryDetail[0][columnName] === undefined) {
        //   this.dateForm.goodsInventoryDetail[0][columnName] = ''
        // }
      },
      doCombination (arr, data) {
        let count = arr.length - 1 // 数组长度(从0开始)
        let tmp = []
        let totalArr = []// 总数组
        let dataTemp = data

        return doCombinationCallback(arr, 0)// 从第一个开始
        // js 没有静态数据，为了避免和外部数据混淆，需要使用闭包的形式
        function doCombinationCallback (arr, currIndex) {
          if (arr.length !== 0) {
            let keys = Object.keys(arr[currIndex])
            for (let i = 0; i < keys.length; i++) {
              tmp[currIndex] = dataTemp[currIndex] + '-' + keys[i]
              // 以curr_index为索引，加入数组
              // 当前循环下标小于数组总长度，则需要继续调用方法
              if (currIndex < count) {
                doCombinationCallback(arr, currIndex + 1)// 继续调用
              } else {
                totalArr.push(tmp)// (直接给push进去，push进去的不是值，而是值的地址)
              }
              // js对象都是 地址引用(引用关系)，每次都需要重新初始化，否则 totalArr的数据都会是最后一次的 tmp 数据；
              let oldTmp = tmp
              tmp = []
              for (let j = 0; j < oldTmp.length; j++) {
                tmp.push(oldTmp[j])
              }
            }
            return totalArr
          }
        }
      },
      addCustomSpecs () {
        this.$http({
          url: this.$http.adornUrl(`/goods/addCustomSpecs`),
          method: 'post',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
          },
          data: qs.stringify({
            'property': this.customSpecs.property,
            'name': this.customSpecs.name
          }, {arrayFormat: 'indices', allowDots: true})
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({duration: 1000,
              message: '添加规格成功',
              type: 'success'
            })

            if (this.specsList.filter(list => list.id === data.data.id).length === 0) {
              this.specsList.push(data.data)
            } else {
              this.specsList.map(list => {
                if (list.id === data.data.id) {
                  data.data.property.map(p => {
                    list.property.push(p)
                  })
                }
              })
            }
            this.customVisible = false
            this.customSpecs.property = []
            this.customSpecs.name = ''
          } else {
            this.$message({duration: 1000,
              message: '添加规格失败',
              type: 'error'
            })
          }
        })
      },
      // 查询自定义规格
      async getCustomSpecs (id) {
        let param = null
        try {
          await this.$http({
            url: this.$http.adornUrl(`/goods/getCustomSpecs/${id}`),
            method: 'get'
          }).then(({data}) => {
            if (data && data.code === 0) {
              param = data.data
            }
          })
        } catch (e) {
          console.log(e)
        }
        return param
      },
      getGoodsDetailByUrl () {
        if (this.taobaoUrl === '') {
          this.$message({
            duration: 1000,
            message: '请填写淘宝链接',
            type: 'error'
          })
          return
        }
        this.loading = true
        axios.post('http://swp8yn.natappfree.cc/getGoodsDetailByUrl', JSON.stringify({
          'url': this.taobaoUrl
        })).then(({data}) => {
          if (data && data.code === 200) {
            this.$refs.ueditor.setUEContent(data.data.goodsDetails)
            this.dateForm.goodsName = data.data.title
            if (data.data.imgs[0] != null) {
              this.dateForm.mainImg.push({id: this.dateForm.photoId, url: data.data.imgs[0].replace('jpg_50x50', 'jpg_800x800')})
            }
            let imgs = data.data.imgs.splice(0, data.data.imgs.length)
            imgs.forEach(i => {
              if (i != null) {
                i = i.replace('jpg_50x50', 'jpg_800x800')
                this.$set(this.dateForm.rollingImg, this.dateForm.rollingImg.length, {id: 0, url: i})
              }
            })
            if (this.dateForm.priceType !== '1') {
              this.dateForm.vipPrice = data.data.price.split('-')[0]
            } else {
              this.dateForm.integral = data.data.price.split('-')[0]
            }

            this.dateForm.goodsInventory = data.data.stock

            // sku
            data.data.sku.forEach((s, index) => {
              Object.keys(s).forEach(v => {
                this.customSpecs.name = v
                data.data.sku[index][v].forEach(p => {
                  this.customSpecs.property.push({id: 0, name: p})
                })
                this.addCustomSpecs()
                this.customSpecs.property = []
                this.customSpecs.name = ''
              })
            })
            this.customSpecs.name = ''
            this.customSpecs.property = []
            this.loading = false
            this.$message({
              duration: 1000,
              message: '爬取成功',
              type: 'info'
            })
          } else {
            this.$message({
              duration: 1000,
              message: data.msg,
              type: 'error'
            })
          }
        })
      },
      // 爬就完事了
      poizon (id) {
        var t = []

        ! function() {
          var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
            n = {
              rotl: function(t, e) {
                return t << e | t >>> 32 - e
              },
              rotr: function(t, e) {
                return t << 32 - e | t >>> e
              },
              endian: function(t) {
                if (t.constructor == Number)
                  return 16711935 & n.rotl(t, 8) | 4278255360 & n.rotl(t, 24);
                for (var e = 0; e < t.length; e++)
                  t[e] = n.endian(t[e]);
                return t
              },
              randomBytes: function(t) {
                for (var e = []; t > 0; t--)
                  e.push(Math.floor(256 * Math.random()));
                return e
              },
              bytesToWords: function(t) {
                for (var e = [], n = 0, i = 0; n < t.length; n++,
                  i += 8)
                  e[i >>> 5] |= t[n] << 24 - i % 32;
                return e
              },
              wordsToBytes: function(t) {
                for (var e = [], n = 0; n < 32 * t.length; n += 8)
                  e.push(t[n >>> 5] >>> 24 - n % 32 & 255);
                return e
              },
              bytesToHex: function(t) {
                for (var e = [], n = 0; n < t.length; n++)
                  e.push((t[n] >>> 4).toString(16)),
                  e.push((15 & t[n]).toString(16));
                return e.join("")
              },
              hexToBytes: function(t) {
                for (var e = [], n = 0; n < t.length; n += 2)
                  e.push(parseInt(t.substr(n, 2), 16));
                return e
              },
              bytesToBase64: function(t) {
                for (var n = [], i = 0; i < t.length; i += 3)
                  for (var o = t[i] << 16 | t[i + 1] << 8 | t[i + 2], r = 0; r < 4; r++)
                    8 * i + 6 * r <= 8 * t.length ? n.push(e.charAt(o >>> 6 * (3 - r) & 63)) : n.push("=");
                return n.join("")
              },
              base64ToBytes: function(t) {
                t = t.replace(/[^A-Z0-9+\/]/gi, "");
                for (var n = [], i = 0, o = 0; i < t.length; o = ++i % 4)
                  0 != o && n.push((e.indexOf(t.charAt(i - 1)) & Math.pow(2, -2 * o + 8) - 1) << 2 * o | e.indexOf(t.charAt(i)) >>> 6 - 2 * o);
                  return n
              }
            };
            t[72] = n
          }()

          ! function() {

            var n = {
              utf8: {
                stringToBytes: function(t) {
                  return n.bin.stringToBytes(unescape(encodeURIComponent(t)))
                },
                bytesToString: function(t) {
                  return decodeURIComponent(escape(n.bin.bytesToString(t)))
                }
              },
              bin: {
                stringToBytes: function(t) {
                  for (var e = [], n = 0; n < t.length; n++)
                    e.push(255 & t.charCodeAt(n));
                  return e
                },
                bytesToString: function(t) {
                  for (var e = [], n = 0; n < t.length; n++)
                    e.push(String.fromCharCode(t[n]));
                  return e.join("")
                }
              }
            };
            t[39] = n

          }()

          ! function() {
            function n(t) {
              return !!t.constructor && "function" == typeof t.constructor.isBuffer && t.constructor.isBuffer(t)
            }

            function i(t) {
              return "function" == typeof t.readFloatLE && "function" == typeof t.slice && n(t.slice(0, 0))
            }
            /*!
            * Determine if an object is a Buffer
            *
            * @author   Feross Aboukhadijeh <https://feross.org>
            * @license  MIT
            */
            t[59] = function(t) {
              return null != t && (n(t) || i(t) || !!t._isBuffer)
            }
          }()

          ! function() {
            var e = t[72],
              i = t[39].utf8,
              o = t[59],
              r = t[39].bin,
              a = function(t, n) {
                t.constructor == String ? t = n && "binary" === n.encoding ? r.stringToBytes(t) : i.stringToBytes(t) : o(t) ? t =
                  Array.prototype.slice.call(t, 0) : Array.isArray(t) || (t = t.toString());
                for (var s = e.bytesToWords(t), c = 8 * t.length, l = 1732584193, d = -271733879, u = -1732584194, p = 271733878, h =
                    0; h < s.length; h++)
                  s[h] = 16711935 & (s[h] << 8 | s[h] >>> 24) | 4278255360 & (s[h] << 24 | s[h] >>> 8);
                s[c >>> 5] |= 128 << c % 32,
                  s[14 + (c + 64 >>> 9 << 4)] = c;
                for (var f = a._ff, m = a._gg, g = a._hh, v = a._ii, h = 0; h < s.length; h += 16) {
                  var A = l,
                    y = d,
                    b = u,
                    x = p;
                  l = f(l, d, u, p, s[h + 0], 7, -680876936),
                    p = f(p, l, d, u, s[h + 1], 12, -389564586),
                    u = f(u, p, l, d, s[h + 2], 17, 606105819),
                    d = f(d, u, p, l, s[h + 3], 22, -1044525330),
                    l = f(l, d, u, p, s[h + 4], 7, -176418897),
                    p = f(p, l, d, u, s[h + 5], 12, 1200080426),
                    u = f(u, p, l, d, s[h + 6], 17, -1473231341),
                    d = f(d, u, p, l, s[h + 7], 22, -45705983),
                    l = f(l, d, u, p, s[h + 8], 7, 1770035416),
                    p = f(p, l, d, u, s[h + 9], 12, -1958414417),
                    u = f(u, p, l, d, s[h + 10], 17, -42063),
                    d = f(d, u, p, l, s[h + 11], 22, -1990404162),
                    l = f(l, d, u, p, s[h + 12], 7, 1804603682),
                    p = f(p, l, d, u, s[h + 13], 12, -40341101),
                    u = f(u, p, l, d, s[h + 14], 17, -1502002290),
                    d = f(d, u, p, l, s[h + 15], 22, 1236535329),
                    l = m(l, d, u, p, s[h + 1], 5, -165796510),
                    p = m(p, l, d, u, s[h + 6], 9, -1069501632),
                    u = m(u, p, l, d, s[h + 11], 14, 643717713),
                    d = m(d, u, p, l, s[h + 0], 20, -373897302),
                    l = m(l, d, u, p, s[h + 5], 5, -701558691),
                    p = m(p, l, d, u, s[h + 10], 9, 38016083),
                    u = m(u, p, l, d, s[h + 15], 14, -660478335),
                    d = m(d, u, p, l, s[h + 4], 20, -405537848),
                    l = m(l, d, u, p, s[h + 9], 5, 568446438),
                    p = m(p, l, d, u, s[h + 14], 9, -1019803690),
                    u = m(u, p, l, d, s[h + 3], 14, -187363961),
                    d = m(d, u, p, l, s[h + 8], 20, 1163531501),
                    l = m(l, d, u, p, s[h + 13], 5, -1444681467),
                    p = m(p, l, d, u, s[h + 2], 9, -51403784),
                    u = m(u, p, l, d, s[h + 7], 14, 1735328473),
                    d = m(d, u, p, l, s[h + 12], 20, -1926607734),
                    l = g(l, d, u, p, s[h + 5], 4, -378558),
                    p = g(p, l, d, u, s[h + 8], 11, -2022574463),
                    u = g(u, p, l, d, s[h + 11], 16, 1839030562),
                    d = g(d, u, p, l, s[h + 14], 23, -35309556),
                    l = g(l, d, u, p, s[h + 1], 4, -1530992060),
                    p = g(p, l, d, u, s[h + 4], 11, 1272893353),
                    u = g(u, p, l, d, s[h + 7], 16, -155497632),
                    d = g(d, u, p, l, s[h + 10], 23, -1094730640),
                    l = g(l, d, u, p, s[h + 13], 4, 681279174),
                    p = g(p, l, d, u, s[h + 0], 11, -358537222),
                    u = g(u, p, l, d, s[h + 3], 16, -722521979),
                    d = g(d, u, p, l, s[h + 6], 23, 76029189),
                    l = g(l, d, u, p, s[h + 9], 4, -640364487),
                    p = g(p, l, d, u, s[h + 12], 11, -421815835),
                    u = g(u, p, l, d, s[h + 15], 16, 530742520),
                    d = g(d, u, p, l, s[h + 2], 23, -995338651),
                    l = v(l, d, u, p, s[h + 0], 6, -198630844),
                    p = v(p, l, d, u, s[h + 7], 10, 1126891415),
                    u = v(u, p, l, d, s[h + 14], 15, -1416354905),
                    d = v(d, u, p, l, s[h + 5], 21, -57434055),
                    l = v(l, d, u, p, s[h + 12], 6, 1700485571),
                    p = v(p, l, d, u, s[h + 3], 10, -1894986606),
                    u = v(u, p, l, d, s[h + 10], 15, -1051523),
                    d = v(d, u, p, l, s[h + 1], 21, -2054922799),
                    l = v(l, d, u, p, s[h + 8], 6, 1873313359),
                    p = v(p, l, d, u, s[h + 15], 10, -30611744),
                    u = v(u, p, l, d, s[h + 6], 15, -1560198380),
                    d = v(d, u, p, l, s[h + 13], 21, 1309151649),
                    l = v(l, d, u, p, s[h + 4], 6, -145523070),
                    p = v(p, l, d, u, s[h + 11], 10, -1120210379),
                    u = v(u, p, l, d, s[h + 2], 15, 718787259),
                    d = v(d, u, p, l, s[h + 9], 21, -343485551),
                    l = l + A >>> 0,
                    d = d + y >>> 0,
                    u = u + b >>> 0,
                    p = p + x >>> 0
                }
                return e.endian([l, d, u, p])
              };
              a._ff = function(t, e, n, i, o, r, a) {
                var s = t + (e & n | ~e & i) + (o >>> 0) + a;
                return (s << r | s >>> 32 - r) + e
              },
              a._gg = function(t, e, n, i, o, r, a) {
                var s = t + (e & i | n & ~i) + (o >>> 0) + a;
                return (s << r | s >>> 32 - r) + e
              },
              a._hh = function(t, e, n, i, o, r, a) {
                var s = t + (e ^ n ^ i) + (o >>> 0) + a;
                return (s << r | s >>> 32 - r) + e
              },
              a._ii = function(t, e, n, i, o, r, a) {
                var s = t + (n ^ (e | ~i)) + (o >>> 0) + a;
                return (s << r | s >>> 32 - r) + e
              },
              a._blocksize = 16,
              a._digestsize = 16;

              t[69] = function(t, n) {
                if (void 0 === t || null === t)
                  throw new Error("Illegal argument " + t);
                var i = e.wordsToBytes(a(t, n));
                return n && n.asBytes ? i : n && n.asString ? r.bytesToString(i) : e.bytesToHex(i)
              }
          }()
        var url = "https://app.poizon.com/api/v1/h5/index/fire/flow/product/detail?productId="+ id +"&productSourceName=shareDetail";
        url += "&sign="+t[69]("productId"+ id +"productSourceNameshareDetail048a9c4943398714b356a696503d2d36");
        return url;
      },
      clickPoizon () {
        if (this.dateForm.poizonId !== '') {
          let poiatt = /^[0-9]*$/
          // if (!poiatt.test(this.dateForm.poizonId)) {
          //   this.$message.error('ID只能为纯数字')
          //   return
          // }
          let goodsId = this.dateForm.poizonId.substring(this.dateForm.poizonId.indexOf('id=') + 3, this.dateForm.poizonId.lastIndexOf('&'))
          if (!poiatt.test(goodsId)) {
            goodsId = this.dateForm.poizonId.substring(this.dateForm.poizonId.indexOf('id=') + 3, this.dateForm.poizonId.length + 1)
            console.log(goodsId)
          }
          // goodsId = goodsId.substring(0, goodsId.indexOf('&'))
          this.dateForm.poizonId = goodsId
        } else {
          this.$message.error('地址不能为空')
          return
        }
        let poizonUrl = this.poizon(this.dateForm.poizonId)
        console.log(poizonUrl)
        if (poizonUrl !== '') {
          // this.$http({
          //   url: this.$http.adornUrl(`/goods/analyticalData/${poizonUrl}`),
          //   methods: 'post',
          //   params: this.$http.adornParams()
          // }).then(({data}) => {
          //   if (data && data.code === 200) {

          //   } else {
          //     this.$message.error(data.msg)
          //   }
          // })
          axios.get(poizonUrl).then(({data}) => {
            if (data && data.code === 200) {
              console.log(data.data.imageAndText.split('body>'))
              let paramData = data.data
              let poiImage = ''
              for (var fff = 0; fff < data.data.detail.images.length; fff++) {
                if (fff === 0) {
                  poiImage = data.data.detail.images[fff].url
                } else {
                  poiImage = poiImage + ',' + data.data.detail.images[fff].url
                }
              }
              this.$http({
                url: this.$http.adornUrl(`/goods/analyticalData`),
                method: 'post',
                data: this.$http.adornData({
                  'images': poiImage,
                  'title': data.data.detail.title,
                  'authPrice': data.data.detail.authPrice,
                  'price': data.data.item.price,
                  'unit': data.data.detail.unit.name,
                  'articleNumber': data.data.detail.articleNumber,
                  'sizeList': data.data.detail.sizeList.join(','),
                  'imageAndText': data.data.imageAndText.split('body>')[1]})
              }).then(({data}) => {
                if (data && data.code === 0) {
                  this.dateForm.goodsInventoryDetail = JSON.parse(data.data.goodsInventoryDetail)
                  this.skuTemp = this.dateForm.goodsInventoryDetail
                  this.getPoiZonSpecsList()
                  debugger
                  this.dateForm.photoId = data.data.photoId
                  this.dateForm.goodsName = data.data.goodsName
                  this.$set(this.dateForm.mainImg, 0, {id: data.data.photoId, url: data.data.img})
                  if (data.data.rotationChart != null && data.data.rotationChart.length > 0) {
                    for (var a = 0; a < data.data.rotationChart.length; a++) {
                      let fileSuffix = data.data.rotationChart[a].url.substring(data.data.rotationChart[a].url.lastIndexOf('.') + 1)
                      if (fileSuffix === 'jpg' || fileSuffix === 'png') {
                        this.dateForm.rollingImg.push({'id': data.data.rotationChart[a].id, 'url': data.data.rotationChart[a].url})
                      } else {
                        this.dateForm.video.push({'id': data.data.rotationChart[a].id, 'url': data.data.rotationChart[a].url})
                      }
                    }
                  }
                  if (this.dateForm.video.length <= 0) {
                    this.videoFlag = true
                  }
                    // this.dateForm.rollingImg.push({id: i, url: pic1[i].imgSrc})
                  this.dateForm.goodsInventory = data.data.goodsInventory
                  this.dateForm.goodsPrice = data.data.goodsPrice
                  this.dateForm.vipPrice = data.data.vipPrice
                  this.dateForm.goodsCostingPrice = data.data.goodsCostingPrice
                  this.dateForm.goodsSerial = data.data.goodsSerial
                  this.$refs.ueditor.setUEContent(data.data.goodsDetails)
                  console.log(data.data.goodsDetails)
                  this.dateForm.giveIntegral = data.data.giveIntegral
                  } else {
                    this.$message.error(data.msg)
                  }
                  // 上传详情图片
                  this.$http({
                    url: this.$http.adornUrl(`/goods/uploadGoodsDetails`),
                    method: 'post',
                    data: this.$http.adornData({
                      'goodsDetails': data.data.goodsDetails
                    })
                  }).then(({data}) => {
                    if (data && data.code === 0) {
                      debugger
                      this.$refs.ueditor.setUEContent(data.data)
                    }
                  })
              })
            } else {
              this.$message.error('数据正在解析中，请稍后！')
              return
            }
          })
        } else {
          this.$message.error('数据正在解析中，请稍后！')
          return
        }
      },
      getPoiZonSpecsList (flag) {
        debugger
        this.$nextTick(function () {
          this.$http({
            url: this.$http.adornUrl(`/goods/querySpecsList/` + this.dateForm.classId[1] || this.dateForm.classId[0]),
            method: 'get'
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.specsList = data.data
              // 回显规格数据
              // if (flag !== null && this.dateForm.id !== 0) {
                let than = this
                than.checkboxData = []
                let idSet = new Set()
                this.dateForm.goodsInventoryDetail.map(gid => gid.id.split('_')).forEach(function (value) {
                  value.forEach(function (val) {
                    if (val !== '' && Number.isInteger(Number.parseInt(val))) {
                      val = Number.parseInt(val)
                      idSet.add(val)
                    }
                  })
                })
                idSet.forEach(function (val) {
                  let ification = than.specsList.filter(item => item.property.map(p => {
                    return p.id
                  }).includes(val))[0]

                  let property
                  if (ification !== undefined) {
                    property = ification.property.filter(item => item.id === val)[0]
                    than.checkboxClick(ification, property)
                    than.checkboxData.push(val)
                  } else {
                    // 自定义规格
                    let customSpecs = null
                    than.getCustomSpecs(val).then(data => {
                      customSpecs = data
                      if (customSpecs !== null) {
                        ification = customSpecs
                        // property = customSpecs.property[0]
                        property = customSpecs.property.filter(p => p.id === val)[0]
                        if (than.specsList.filter(list => list.id === data.id).length === 0) {
                          than.specsList.push(customSpecs)
                        } else {
                          than.specsList.map(list => {
                            if (list.id === data.id) {
                              // than.specsList.push(customSpecs)
                              list.property.push(property)
                            }
                          })
                        }
                        than.checkboxClick(ification, property)
                        than.checkboxData.push(val)
                      }
                    })
                  }
                })
              // }
            }
          })
          // 请求关联品牌
          debugger
          this.$http({
            url: this.$http.adornUrl(`/brand/queryBrandList/` + this.dateForm.classId[1]),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.brandList = data.data
            }
          })
        })
        if (!this.dateForm.id) {
          debugger
          this.videoFlag = true
        }
      },
      // 随机库存
      randomGoodsInventory () {
        let upper = 1000
        let lower = 300
        for (let n = 0; n < this.dateForm.goodsInventoryDetail.length; n++) {
          this.dateForm.goodsInventoryDetail[n].count =  Math.floor(Math.random() * (upper - lower+1)) + lower
        }
      },
      // 验证型号是否已经存在
      verificationGoodsSerial () {
        this.$http({
          url: this.$http.adornUrl(`/goods/verificationGoodsSerial/${this.dateForm.goodsSerial}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            if (data.data !== 0) {
              this.$message.error('该型号已经存在')
              this.dateForm.goodsSerial = ''
            }
          } else {
            this.$message.error(data.msg)
          }
        })
      }
    }
  }
</script>
<style >
  .upload-goods .el-input--medium .el-input__inner {
    width: 300px;
  }
  .upload-goods .el-textarea__inner{
    width: 300px;
  }
  .upload-goods .el-table__row .el-input__inner{
    width: 150px;
  }
  .upload-goods .specs .el-card__body .el-col {
    margin-left: 20px;
    margin-bottom: 10px;
  }

  .upload-goods .specs .card{
    margin-left: 45px;
    height: 200px !important;
    overflow-y: visible;
    margin-bottom: 5px;
  }
  .specs-table .el-table__row .el-input__inner{
    width: 100% !important;
  }

  .specsImg .el-row{
    margin-left: 5px !important;
  }

  .specsImg .el-col-4 {
    width: 16.66667%;
    padding-top: 35px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
  .upload-goods .el-col .el-form-item{
    margin-bottom: 22px !important;
  }
  .custom .el-tag + .el-tag {
    margin-left: 10px;
  }
  .custom .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .custom .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .el-cascader-menu {
    height: 400px;
  }
</style>
